// Kokomi.js - Three.js 组件框架
import * as kokomi from "kokomi.js";
// Three.js - 3D 渲染引擎
import * as THREE from "three";

import type Experience from "../Experience";

// 测试对象的自定义着色器
import testObjectVertexShader from "../Shaders/TestObject/vert.glsl";
import testObjectFragmentShader from "../Shaders/TestObject/frag.glsl";

/**
 * 测试对象组件
 * 用于开发和调试着色器效果
 * 默认未在项目中使用（已注释掉）
 */
export default class TestObject extends kokomi.Component {
  declare base: Experience; // Experience 实例引用
  material: THREE.ShaderMaterial; // 自定义着色器材质
  mesh: THREE.Mesh; // 测试网格
  uj: kokomi.UniformInjector; // Uniform 注入器
  
  constructor(base: Experience) {
    super(base);

    // 着色器参数
    const params = {
      uDistort: {
        value: 1, // 扭曲强度
      },
    };

    // 创建球体几何体（64x64 细分）
    const geometry = new THREE.SphereGeometry(2, 64, 64);
    // const geometry = new THREE.PlaneGeometry(4, 4); // 可选：平面几何体
    
    // 创建自定义着色器材质
    const material = new THREE.ShaderMaterial({
      vertexShader: testObjectVertexShader,
      fragmentShader: testObjectFragmentShader,
    });
    this.material = material;
    
    // 创建网格
    const mesh = new THREE.Mesh(geometry, material);
    this.mesh = mesh;

    // 创建 Uniform 注入器
    const uj = new kokomi.UniformInjector(this.base);
    this.uj = uj;
    
    // 合并 uniforms
    material.uniforms = {
      ...material.uniforms,
      ...uj.shadertoyUniforms, // Shadertoy 风格的 uniform
      ...params, // 自定义参数
    };

    // 如果开启了调试模式，添加调试面板
    const debug = this.base.debug;
    if (debug.active) {
      const debugFolder = debug.ui?.addFolder("testObject");
      debugFolder
        ?.add(params.uDistort, "value")
        .min(0)
        .max(2)
        .step(0.01)
        .name("distort");
    }
  }
  /**
   * 将测试对象添加到场景
   */
  addExisting() {
    this.container.add(this.mesh);
  }
  
  /**
   * 每帧更新，注入 Shadertoy uniforms
   */
  update() {
    this.uj.injectShadertoyUniforms(this.material.uniforms);
  }
}
